/*
 * @Description: 发运自动化规则页面
 * @Version: 1.0
 * @Autor: c-jack.qian
 * @Date: 2020-10-21 17:30:52
 * @LastEditors: c-jack.qian
 * @LastEditTime: 2021-04-25 16:58:42
 */
import React, { useMemo, useRef } from 'react';
import { PageHeaderWrapper } from 'hzero-boot/lib/components/Page';
import {
  Button,
  DataSet,
  Form,
  Modal,
  notification,
  Select,
  Table,
  TextField,
} from 'choerodon-ui/pro';
import { FuncType } from 'choerodon-ui/pro/lib/button/enum';
import { useDataSet } from 'hzero-front/lib/utils/hooks';
import { DataSetProps } from 'choerodon-ui/pro/lib/data-set/DataSet';
import { connect } from 'dva';
import { ColumnLock, TableColumnTooltip } from 'choerodon-ui/pro/lib/table/enum';
import intl from 'utils/intl';
import { routerRedux } from 'dva/router';
import querystring from 'querystring';
import request from 'utils/request';

import {
  shippingAutomationRulesDS,
  modalRulesDataSet,
} from '../../stores/shippingAutomationRulesDS';
import { renderSort, addEnterCallBack } from '../../utils/utilsFun';
import CustomizeTableSearch from '@common/components/CustomizeTableSearch';
import formatterCollections from 'utils/intl/formatterCollections';
import { getAccessToken } from 'hzero-front/lib/utils/utils';
import commonConfigStore from '@common/config/commonConfig';
const O2_OM = process.env.NODE_ENV === 'development' ? '/o2om-c-cmy' : commonConfigStore.O2_OM;

notification.config({
  duration: 3,
  placement: 'bottomRight',
});
interface propstype {
  dispatch: any;
}

const ClassPage: React.FC<propstype> = ({ dispatch }) => {
  const tableDS = useDataSet(() => new DataSet(shippingAutomationRulesDS() as DataSetProps));
  const modalDS = useDataSet(() => new DataSet(modalRulesDataSet() as DataSetProps));

  const pageRef = useRef(null);

  // 添加按回车查询事件
  addEnterCallBack(tableDS, pageRef);

  // 删除选择行
  const handleDelete = () => {
    const seletedRecord = tableDS.selected;
    if (seletedRecord.length === 0) {
      notification.warning({
        placement: 'bottomRight',
        message: intl.get(`dji.otc.om.view.reminder.warning`).d('提示'),
        description: intl.get(`dji.otc.om.view.reminder.selectDeleteData`).d('请勾选删除的数据'),
      });
      return;
    }
    tableDS.delete(seletedRecord);
  };

  const Columns = useMemo<any>(
    () => [
      {
        header: intl.get(`dji.otc.om.view.field.serialNumber`).d('序号'),
        width: 50,
        lock: true,
        renderer: ({ record }) => renderSort(record, tableDS),
      },
      { name: 'businessGroupCode', align: 'left', tooltip: TableColumnTooltip.always },
      { name: 'areaId', align: 'left', tooltip: TableColumnTooltip.always },
      { name: 'customerName', align: 'left', tooltip: TableColumnTooltip.always },
      { name: 'tradeTerm', align: 'left', tooltip: TableColumnTooltip.always },
      { name: 'logistics', align: 'left', tooltip: TableColumnTooltip.always },
      { name: 'shippingAmount', align: 'left', tooltip: TableColumnTooltip.always },
      { name: 'shippingWeight', align: 'left', tooltip: TableColumnTooltip.always },
      { name: 'automationRule', align: 'left', tooltip: TableColumnTooltip.always },
      { name: 'automationCycle', align: 'left', tooltip: TableColumnTooltip.always },
      {
        header: intl.get('dji.otc.om.view.field.sentSetDefaultValue').d('发运通知单默认值设置'),
        width: 150,
        lock: ColumnLock.right,
        command: ({ record }) => {          
          return [
            <Button
              funcType={'flat' as FuncType}
              key="look"
              onClick={() => {
                checkDetailModal(record, 'edit');
              }}
            >
              <a key="look">{intl.get(`dji.otc.om.view.button.edit`).d('编辑')}</a>
            </Button>,
          ];
        },
      },
    ],
    []
  );

  const checkDetailModal = async (record, type) => {
    const ruleId = record.get('ruleId')
    if (type === 'create') {
      modalDS.create({});
    } else {
      modalDS.setQueryParameter('ruleId', ruleId)
      await modalDS.query()
    }

    Modal.open({
      key: 'modal',
      title: intl.get(`dji.otc.om.view.title.editShippingAutomationRules`).d('编辑发运自动化规则'),
      closable: true,
      drawer: true,
      children: (
        <div>
          <Form dataSet={modalDS} columns={1} labelWidth={140}>
            <Select name="lmsLogistics" />
            <Select name="shippingAddress" />
            <Select name="isShowModelNumber" />
            <Select name="isShowCiPoNumber" />
            <Select name="emailAddress" />
            <Select name="shippingWarehouse" />
            <Select name="customerEmailAddress" />
            <Select name="deliverDate" />
            <Select name="arrivalDate" />
            <Select name="ciConfirm" />
            <Select name="overallShipment" />
            <Select name="dealerOwnAccount" />
            <Select name="ciAttribute" />
          </Form>
        </div>
      ),
      onCancel: () => modalDS.reset(),
      onOk: () => modalDS.submit().then(() => tableDS.query()),
    });
  };

  const handleBatchExport = () => {
    dispatch(
      routerRedux.push({
        pathname: `/o2om/distribution/excel-import/O2OM_C.SHIPPING_AUTO_RULE`,
        search: querystring.stringify({
          action: intl.get(`dji.otc.om.view.title.shippingAutomationRulesImport`).d('发运自动化规则列表导入'),
          prefixPath: 'O2OM_C.SHIPPING_AUTO_RULE',
        }),
      })
    );
  };

  
  const handleExportModel = () => {
    const accessToken = getAccessToken();
    request(
      `${O2_OM}/v1/0/import/template/O2OM_C.SHIPPING_AUTO_RULE/excel?access_token=${accessToken}&type=bpmn20`,
      {
        method: 'GET',
        responseType: 'blob',
      }
    ).then(res => {
      if (res) {
        const bl = new Blob([res]);
        const fileName = intl
          .get('dji.otc.om.view.title.shippingAutomationRulesImportModel')
          .d('发运自动化规则列表导入模版');
        const link = document.createElement('a');
        document.body.appendChild(link);
        link.style.display = 'none';
        link.href = window.URL.createObjectURL(bl);
        link.download = `${fileName}.xlsx`;
        link.click();
        document.body.removeChild(link);
      }
    });
  };

  return (
    <PageHeaderWrapper
      title={intl.get('dji.otc.om.view.menu.shippingAutomationRules').d('发运自动化规则')}
      header={
        <div style={{ display: 'flex', alignItems: 'center' }}>
          <Button icon="get_app" key="import" onClick={() => handleBatchExport()}>
            {intl.get(`dji.otc.om.view.button.improtModel`).d('导入模板')}
          </Button>
          <Button icon="export" key="export" onClick={() => handleExportModel()}>
            {intl.get(`dji.otc.om.view.button.exportMode`).d('导出模板')}
          </Button>
          <Button onClick={() => handleDelete()}>
            {intl.get(`dji.otc.om.view.button.delete`).d('删除')}
          </Button>
          {/* <Button onClick={() => checkDetailModal(null, 'create')} color={ButtonColor.primary} >
            {intl.get(`dji.otc.om.view.button.create`).d('新建')}
          </Button> */}
        </div>
      }
    >
      <div ref={pageRef}>
        <Table
          dataSet={tableDS}
          border
          queryFieldsLimit={3}
          columns={Columns}
          queryBar={props => (
            <CustomizeTableSearch
              elements={[
                <Select name="businessGroup" key="businessGroup" searchable />,
                <Select name="areaId" key="areaId" searchable />,
                <TextField name="customerName" key="customerName" />,
              ]}
              // eslint-disable-next-line react/jsx-props-no-spreading
              {...props}
            />
          )}
        />
      </div>
    </PageHeaderWrapper>
  );
};
export default connect()(
  formatterCollections({
    code: 'dji.otc.om',
  })(ClassPage)
);
